import {
  queryUserInfoReq,
  queryMenuListReq,
  queryBrandInfoReq,
} from "@/services/global";
import * as icons from "@ant-design/icons";
import Icon from "@ant-design/icons";
import { setItem } from "@/utils/localstorage";
const delMenu = (arr) => {
  return arr.map((item) => ({
    ...item,
    name: item.meta.title,
    hideInMenu: item.hidden,
    target: "_blank",
    icon: (
      <Icon component={icons[item.meta.icon]} style={{ marginRight: "8px" }} />
    ),
    children: item.children ? delMenu(item.children) : null,
  }));
};
export default {
  namespace: "global",
  state: {
    init: false,
    menu: [],
    user: {},
    roles: [],
    permissions: [],
    data: [1, 2, 3],
    GMap: {},
    GMapConf: {
      center: [118.781513, 32.018791],
      zoom: 11,
    },
    messageCount: 0,
    brandInfo: {},
    hasLeftMenu: false,
  },
  effects: {
    *queryUserInfo({ params }, { call, put }) {
      const res = yield call(queryUserInfoReq, params);
      if (res) {
        const tempMenu = yield call(queryMenuListReq, res?.user.roleId);
        const menu = delMenu(tempMenu);
        if (menu.length == 0) {
          yield put({
            type: "save",
            payload: {
              hasLeftMenu: true,
            },
          });
        }
        setItem("userInfo", res.user);
        setItem("permissions", res.permissions);
        yield put({
          type: "save",
          payload: {
            ...res,
            menu,
            init: true,
          },
        });
      }
    },
    *queryMessage({ params }, { call, put }) {
      yield put({
        type: "save",
        payload: {
          messageCount: params.count,
        },
      });
    },
    *queryUserInfoObj({ params }, { call, put }) {
      const res = yield call(queryUserInfoReq, params);
      if (res) {
        yield put({
          type: "save",
          payload: {
            ...res,
          },
        });
      }
    },
    *queryBrandInfo({ params }, { call, put }) {
      const res = yield call(queryBrandInfoReq, params);
      if (res) {
        yield put({
          type: "save",
          payload: {
            brandInfo: res,
          },
        });
      }
    },
    *queryHiddenLeftMenu({ params }, { call, put }) {
      yield put({
        type: "save",
        payload: {
          hasLeftMenu: params.status,
        },
      });
    },
  },
  reducers: {
    save(state: any, { payload }: any) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
